package com.lovo.action;

import com.auth0.jwt.JWT;
import com.google.gson.Gson;
import com.lovo.bean.User;
import com.lovo.service.IUserService;
import com.lovo.service.impl.UserServiceImpl;
import com.lovo.util.CodeMsg;
import com.lovo.util.JwtUtil;
import com.lovo.util.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "UserServlet",urlPatterns = "/user.do")
public class UserServlet extends HttpServlet {
    private IUserService ius = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String method = request.getParameter("method");
        if (method == null || method.equals("")) {

        } else if (method.equals("registeUser")) {
            registeUser(request, response);
        } else if (method.equals("login")) {
            userLogin(request, response);
        } else if(method.equals("verify")){
            verifyUser(request,response);
        }
    }

    protected void registeUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");
        String userDate = request.getParameter("userDate");
        //日期转换
        String userTel = request.getParameter("userTel");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = sdf.parse(userDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        User u = new User(userName, userPwd, date, userTel);
        Result<User> r = null;
        boolean b = ius.insertUser(u);
        if (b) {
            r = Result.success(u);
        } else {
            r = Result.error(CodeMsg.SERVER_ERROR);

        }
        Gson g = new Gson();
        String json = g.toJson(r);
        response.getWriter().write(json);

    }
    protected void userLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userTel = request.getParameter("userTel");
        String userPwd = request.getParameter("userPwd");
        User u =new User();
        u.setUserTel(userTel);
        u.setUserPwd(userPwd);
        User user = ius.userLogin(u);
        Result<User> r=null;
        if(user!=null&&user.getUserId()>0){
            r=Result.success(user);
            String token = JwtUtil.createJWT(6000000,user);
            response.setHeader("Authorization",token);
        }else{
            r =Result.error(CodeMsg.SERVER_ERROR);
        }
        String json = new Gson().toJson(r);
        response.getWriter().write(json);


    }
    protected void verifyUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String authHeader =request.getHeader("authorization");
        System.out.println("authHeader = " + authHeader);
        String token =authHeader.substring(7);
        int userId;
        userId = JWT.decode(token).getClaim("id").asInt();
        User u = ius.getUserById(userId);

        Result<User> r =null;
        if(u!=null){
            Boolean verify = JwtUtil.isVerify(token, u);
            if(verify){
                r =Result.success(u);
            }else{
                r =Result.error(CodeMsg.PASSWORD_ERROR);
            }
        }else{
            r = Result.error(CodeMsg.NOTFOUND_ERROR);
        }
        String json = new Gson().toJson(r);
        response.getWriter().write(json);

    }
}
